<template>
	<view class="live-room-section" :class="config.style">
		<FullscreenLoading :loading="!loadDataEnd" :config="config"></FullscreenLoading>
		<view class="play-section">
			<view class="obs-section" v-if="pushType=='obs'">
				<view class="obs-player" v-if="pushStatus==1">
					<video id="myVideo" class="video" :src="roomData.play_url.m3u8" @error="videoErrorCallback" :controls="videoControls" autoplay></video>
				</view>
				<view class="obs-player" v-if="pushStatus==0">
					<image class="image" :src="roomData.cover_400" mode="widthFix"></image>
					<view class="tip-box">
						<view class="tip">{{tip}}</view>
					</view>
				</view>
			</view>
			<view class="webtrc-section" v-if="pushType=='web'">
				<view v-if="pushStatus == 1" class="webtrc-live">
					<!--小程序端暂不支持webtrc直播方式-->
					<view class="web-player">
						<image class="image" :src="roomData.cover_400" mode="widthFix"></image>
						<view class="tip-box">
							<view class="tip">小程序端暂不支持webtrc直播方式</view>
						</view>
					</view>
				</view>
				<view v-else class="webtrc-live">
					<!--小程序端暂不支持webtrc直播方式-->
					<view class="web-player">
						<image class="image" :src="roomData.cover_400" mode="widthFix"></image>
						<view class="tip-box">
							<view class="tip">小程序端暂不支持webtrc直播方式</view>
						</view>
					</view>
				</view>
			</view>
			
		</view>
		<!--互动区域-->
		<view class="interact-section" >
			<view class="tabs">
				<ListTabs v-model="tabIndex" :tabs="tabs" @change="tabChange"></ListTabs>
			</view>
			
			<view id="content" class="content" >
				<template v-if="loadDataEnd">
					<TcTim ref="tcTim" :config="config" :userInfo="userInfo" :roomData="roomData" />
				</template>
			</view>
			
		</view>
	</view>
</template>

<script>
	import TcTim from '../common/tcTim'
	import ListTabs from "@/common/components/listTabs"; //列表tab
	export default {
		components: {
			TcTim,
			ListTabs,
		},
		data() {
			return {
				contentHeight: 0, // 互动区域高度
				loadDataEnd: false, // 数据是否加载完成
				tabs: ['互动', '在线', '课程', '教师'],
				tabIndex: 0 ,// tab下标
				videoControls: false, // 播放器控制栏
				config: {},
				urlParams: {},
				userSig : '',
				userID : 0,
				userInfo: {},
				sdkAppId : '',
				roomID : 0, // 房间ID
				roomData : {}, // 房间数据
				pushType : '', // 推流类型
				pushStatus : 0, // 推流状态
				tip: '直播未开始',
				nodes: [{
					name: 'div',
					attrs: {
						class: 'div-class',
						style: 'line-height: 60px; color: red; text-align:center;'
					},
					children: [{
						type: 'text',
						text: 'Hello&nbsp;uni-app!'
					}]
				}],
			}
		},
		onLoad(option) { //option为object类型，会序列化上个页面传递的参数
		    //console.log(option); //打印出上个页面传递的参数。
			this.initData()
		},
		onReady() {
			let that=this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					console.log(res)
					let pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					//console.log(pH)
					let contentH = uni.createSelectorQuery() //想要获取高度的元素名（class/id）
					
					contentH.in(that).select(".interact-section").boundingClientRect(data=>{
						//console.log(data)
						that.contentHeight = pH-data.top  //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
						//console.log(that.contentHeight)
					}).exec()
				}
			})
		},
		created() {
			this.videoContext = uni.createVideoContext('myVideo')
			
		},
		methods: {
			
			videoErrorCallback(e) {
				//console.log(e)
				this.tip = '直播已结束'
				this.videoContext.stop()
			},
			async initData(){
				await this.getUrlParam()
				await this.getConfig()
				await this.getUserInfo()
				await this.getRoomData()
				//每10秒执行一次getRoomPush()方法
				setInterval(() => {
				    // 同上	
					this.getRoomData()
				}, 10000)
			},
			/**
			 * 设置组件高度
			 */
			setMsgBlockHeight: function(){
				const query = uni.createSelectorQuery().in(this);
				query.select('.play-section').boundingClientRect(data => {
					console.log('set block height')
					console.log(data)
				}).exec();
				query.select('.content').boundingClientRect(data => {
					console.log(data)
				}).exec();
			},
			//获取url参数
			getUrlParam: function(){
				// #ifdef MP-WEIXIN
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = routes[routes.length - 1].route //获取当前页面路由
				let curParam = routes[routes.length - 1].options; //获取路由参数
				// #endif
			
				// #ifdef H5
				let curParam = this.$route.query;
				// #endif
				this.urlParams = curParam
			},
			/**
			 * 获取配置
			 */
			getConfig: function(){
				let that = this
				const config = uni.getStorageSync('config');
				if(config){
					that.config = config
					this.getUserInfo()
				}else{
					//获取全局配置
					this.util.request({
						url : 'entry/wxapp/config',
						data: {
							'm' : 'muu_classroom'
						},
						success: function (res) {
							//console.log(res.data);
							if (res.data.code == 200) {
								that.config = res.data.data
							}
						}
					})
				}
			},
			
			/**
			 * 获取用户数据
			 */
			getUserInfo: function(){
				let that = this
				let userInfo = uni.getStorageSync('userInfo') || {};
				let data = {}
					data.action = 'user_info'
					data.m = 'muu_classroom'
				//获取首页数据
				this.util.request({
					url : 'entry/wxapp/ucenter',
					data : data,
					success: function (res) {
						if (res.data.code == 200) {
							//console.log(res.data.data)
							userInfo.memberInfo = res.data.data;
							uni.setStorageSync('userInfo', userInfo);
							that.userInfo = userInfo
						}
					}
				})
			},

			/**
			 * 获取直播间详情数据
			 */
			getRoomData: function(){
				let _this = this
				let params = this.urlParams
				let data = {}
					data.action = 'room'
					data.m = 'muu_classroom'
					data.id = params.id
				//获取首页数据
				this.util.request({
					url : 'entry/wxapp/livecourse',
					data : data,
					success: function (res) {
						if (res.data.code == 200) {
							console.log(res.data.data)
							_this.roomID = Number(res.data.data.id);
							_this.roomData = res.data.data;
							_this.pushType = res.data.data.push_type;
							_this.pushStatus = res.data.data.push_status;
							_this.loadDataEnd = true
							//obs推流执行
							if(_this.pushType == 'obs'){
								_this.obsPushStream();
							}
							//web推流执行
							if(_this.pushType == 'web'){
								_this.webPushStream();
							}
						}
					}
				})
			},
			
			//obs推流直播执行
			obsPushStream: function() {
				var _this = this;
				
				//this.videoPlayer = uni.createVideoContext('myVideo')
				if(this.pushType == 'obs' && this.pushStatus == 1){
					this.videoContext.play()
					console.log('obs推流播放');
					//实例化播放器
					var cover = _this.roomData.cover_400;
					//var flv = _this.roomData.play_url.flv;
					var m3u8 = _this.roomData.play_url.m3u8;
				}else{
					
					//销毁后清空该变量，必须写这句，要不不好用
					//this.tip = '直播已结束';
				}
			},
			
			//web端推流执行
			webPushStream: function() {
				var _this = this;
				if(this.pushType == 'web'){
					console.log('实时音视频播放');
				}
			},
			
			/**
			 * 退出课堂
			 */
			quitClassroom: function() {
				let _this = this;
				let promise = this.tim.logout();
					promise.then(function(imResponse) {
						console.log(imResponse.data); // 登出成功
						_this.status = _this.STATUS_LOGINED;
						_this.showMessageInBox('课堂助手', "退出课堂成功");
						_this.clearClassInfo();
					}).catch(function(imError) {
						console.warn('logout error:', imError);
					});
			},
			
			tabChange: function(e){
				console.log(e)
			}
			
		}
	}
</script>

<style lang="scss">
	
	.live-room-section {
		height: 100vh;
		display: flex;
		flex-flow: column;
		
	}
	.play-section {
		
		.obs-player {
			position: relative;
			.video {
				width: 100%;
			}
			
			.image {
				width: 100%;
				display: block;
			}
			.tip-box {
				position: absolute;
				top: 50%;
				left: 0;
				right: 0;
				height: 36px;
				z-index: 5;
				margin-top: -18px;
				.tip {
					color: #fff;
					background: rgba(0,0,0,.5);
					text-align: center;
					width: 180px;
					margin: 0 auto;
					padding: 10px;
					border-radius: 5px;
				}
			}
		}
	}
	
	.webtrc-section {
		position: relative;
		.webtrc-live {
			
		}
	}
	
	.interact-section {
		background-color: #f8f8f8;
		display: flex;
		flex-flow: column;
		flex: 1;
		.tabs {
			height: 32px;
		}
		.content {
			position: relative;
			flex: 1;
		}
	}
	

</style>
